#!/usr/bin/env python3
# main.py
import json
import network
import time
import random
from machine import ADC, Pin
from umqtt.simple import MQTTClient

# ========== User Configurable Area ==========
WIFI_SSID = "xxx"
WIFI_PASS = "xxx"
ADC_PIN   = 16            # ADC0 pin of ESP32-P4
MQTT_SERVER = "192.168.31.160"
MQTT_PORT   = 32768
MQTT_CLIENT_ID = 'micropython-client-{id}'.format(id=random.getrandbits(8))
MQTT_USER   = "xxx"
MQTT_PASS   = "xxx"
PUB_TOPIC   = "esp/adc/temp"
PUB_INTERVAL = 2         # Publishing interval (seconds)
# ===================================
def wifi_connect(ssid, pwd):
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    if not sta.isconnected():
        print("Connecting Wi-Fi...")
        sta.connect(ssid, pwd)
        for _ in range(20):
            if sta.isconnected():
                break
            time.sleep(1)
    print("Wi-Fi connected:", sta.ifconfig())
# --------------- Temperature Conversion ---------------
def read_temperature():
    """
    Linear conversion:
    Reference voltage 3.3 V, temperature sensor output 10 mV/°C
    """
    adc = ADC(Pin(ADC_PIN))
    adc.atten(ADC.ATTN_11DB)       # 0-3.3 V
    raw = adc.read()
    volt = raw / 4095 * 3.3        # ADC voltage
    temp = (volt - 1.4) * 100      # ADC temperature
    return round(temp, 1)

# --------------- MQTT Connection ---------------
def mqtt_connect():
    c = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT,
                   MQTT_USER, MQTT_PASS)
    c.connect()
    print("[MQTT] Connected to", MQTT_SERVER)
    return c

def mqtt_publish(client, data: dict):
    payload = json.dumps(data)
    client.publish(PUB_TOPIC, payload)
    print("[MQTT] Sent ->", payload)

# --------------- Main Function ---------------
def main():
    wifi_connect(WIFI_SSID, WIFI_PASS)  # Connect WiFi
    client = mqtt_connect()
    while True:
        temp = read_temperature()
        mqtt_publish(client, {"temperature": temp})
        time.sleep(PUB_INTERVAL)

if __name__ == "__main__":
    main()